package com.example.guiguiapplicatio.fragment.home;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.guiguiapplicatio.api.InsertRecordApi;
import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.Interface.InsertRecordCallback;
import com.example.guiguiapplicatio.api.ListenerClusteringApi;
import com.example.guiguiapplicatio.Layout.LabelGridLayout;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.util.FilterBean;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
//人群标签
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NewSigningFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewSigningFragment extends Fragment implements AllCallback, InsertRecordCallback {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    //人群标签
    private LabelGridLayout lglLabel;
    private TextView tvReset;
    private TextView tvConfirm;
    private ImageButton ibBack;
    private Button commitBtn;
    //建档
    private EditText etName;
    private EditText etId;
    private EditText etEthnic;
    private EditText etSex;
    private EditText etBirthData;
    private EditText etTelephone;
    private EditText etResidence;
    private EditText etDetailedresidence;
    //建档
    private boolean isMul;
    private ListenerClusteringApi listenerClusteringApi;
    private List<FilterBean> labelLists = new ArrayList<>();
    private List<Object> dataList;
    private InsertRecordApi insertRecordApi;
    private List<Integer> peopleidlist;


    public NewSigningFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewSigningFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NewSigningFragment newInstance(String param1, String param2) {
        NewSigningFragment fragment = new NewSigningFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_signing, container, false);
        peopleidlist = new ArrayList<>();
        lglLabel = view.findViewById(R.id.lgl_label);
        tvReset = view.findViewById(R.id.tv_reset);
        tvConfirm = view.findViewById(R.id.tv_confirm);
        ibBack = view.findViewById(R.id.servic_back);
//        建档
        commitBtn = view.findViewById(R.id.comit_btu);
        etName = view.findViewById(R.id.et_name);
        etId = view.findViewById(R.id.et_id);
        etEthnic = view.findViewById(R.id.et_ethnic);
        etSex = view.findViewById(R.id.et_sex);
        etBirthData = view.findViewById(R.id.et_birthData);
        etTelephone = view.findViewById(R.id.et_telephone);
        etDetailedresidence = view.findViewById(R.id.et_detailedresidence);
//        建档
        insertRecordApi=new InsertRecordApi();
        insertRecordApi.setInsertRecordCallback(this);
        listenerClusteringApi = new ListenerClusteringApi();
        listenerClusteringApi.setAllCallback(this);
        showCityPicker(view);
        // 添加空检查
        Bundle args = getArguments();
        if (args != null) {
            isMul = args.getBoolean("isMul", true);
        } else {
            // 如果参数为空，设置默认值
            isMul = true; // 或者您可以设置为您认为合适的默认值
        }
        listenerClusteringApi.performShowListener();
//        initData();
//        setViewData();
        commitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String etname = etName.getText().toString();
                String etid = etId.getText().toString();
                String etethnic = etEthnic.getText().toString();
                String etsex = etSex.getText().toString();
                String etbirthData = etBirthData.getText().toString();
                String ettelephone = etTelephone.getText().toString();
                String etresidence = etResidence.getText().toString();
                String etdetailedresidence = etDetailedresidence.getText().toString();

                if (TextUtils.isEmpty(etname) || TextUtils.isEmpty(etid) || TextUtils.isEmpty(etethnic) ||
                        TextUtils.isEmpty(etresidence) || TextUtils.isEmpty(etdetailedresidence) ||
                        TextUtils.isEmpty(etbirthData) || TextUtils.isEmpty(ettelephone) || TextUtils.isEmpty(etsex)) {
                    Toast.makeText(getContext(), "请确保所有字段都填写完整", Toast.LENGTH_SHORT).show();
                } else {
                    // 所有参数都不为空，执行插入操作
                    insertRecordApi.performInsertRecord(etname, etid, etethnic, etresidence, etdetailedresidence,
                            etbirthData, ettelephone, etsex, peopleidlist,getContext());
                    Navigation.findNavController(v).navigate(R.id.action_newSigningFragment_to_recordSuccessFragment);
                }
            }
        });
        ibBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigate(R.id.action_newSigningFragment_to_navigation_home);
            }
        });

        tvReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lglLabel.resetData();
                peopleidlist.clear();

            }
        });

        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> selectedLabels = lglLabel.getLabelData();
           peopleidlist.clear();
                for (String label : selectedLabels) {
                    String[] parts = label.split("\\."); // 使用 "." 进行分割
                    if (parts.length == 2) { // 确保有两个部分
                        try {
                            int id = Integer.parseInt(parts[0]); // 提取整数部分
                            peopleidlist.add(id); // 将ID添加到列表中
                        } catch (NumberFormatException e) {
                            // 忽略无效的ID
                            Log.e("Error", "Invalid ID: " + parts[0]);
                        }
                    } else {
                        // 格式错误，忽略该标签
                        Log.e("Error", "Invalid label format: " + label);
                    }
                }

                // 打印提取后的ID列表
                Log.d("info", peopleidlist.toString());
            }
        });

        return view;
    }


    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
        // 模拟从后端获取 CheckBox 的文本内容

    }

    // 模拟从后端获取 CheckBox 文本内容的方法
//人群标签
    private void initData(List<Object> dataList) {

        labelLists.clear();
        for (Object item : dataList) {
            if (item instanceof Map) {
                Map<String, Object> itemMap = (Map<String, Object>) item;;
                Object name = itemMap.get("name");
                Object id=itemMap.get("id");
                if (name != null && id != null) {
                    int intid=(int)(double)id;
                    String labelName=String.format("%d.%s",intid,name);
                    List<FilterBean.TableMode> label = new ArrayList<>();
                    label.add(new FilterBean.TableMode(labelName));
                    labelLists.add(new FilterBean(new FilterBean.TableMode("全部"), label));
                }
            }
        }
        setViewData();
    }

    private void setViewData() {
        lglLabel.setColumnCount(4);
        lglLabel.setMulEnable(true);
        lglLabel.setLabelBg(R.drawable.flow_popup);
        lglLabel.setGridData(labelLists);
    }

    @Override
    public void onSuccess(ResponseBody<Object> responseBody) {
        Object data = responseBody.getData();
        if (data instanceof List) {
            dataList = (List<Object>) data;
            // 在主线程中更新视图数据
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    initData(dataList);
                }
            });
        }
    }

    @Override
    public void onFailure(String errorMessage) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "人群列表响应失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void insertSuccess(ResponseBody<Object> responseBody) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "建档响应成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void insertFailure(String errorMassage) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "建档响应失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void showCityPicker(View view){

        final CityPickerView cityPicker=new CityPickerView();
        cityPicker.init(getContext());
        CityConfig cityConfig = new CityConfig.Builder()
                .province("广西壮族自治区")//默认显示的省份
                .city("桂林市")//默认显示省份下面的城市
                .district("灵川县")//默认显示省市下面的区县数据
                .build();
        cityPicker.setConfig(cityConfig);
        etResidence=view.findViewById(R.id.et_residence);
        etResidence.setFocusable(false);
        etResidence.setFocusableInTouchMode(false);
        etResidence.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    //点击确定
                    public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                        etResidence.setText(province+String.valueOf(city)+district);
                    }
                    @Override
                    //点击取消
                    public void onCancel() {
                    }
                });
                cityPicker.showCityPicker();
            }
        });
    }

}